<template>
  <view class="container">
    <!-- 公告区域 -->
    <view v-if="noticeList.length > 0" class="notice-section">
      <view class="notice-header">
        <view class="notice-title">
          <uni-icons type="sound" size="16" color="#007aff"></uni-icons>
          <text class="notice-title-text">公告通知</text>
        </view>
      </view>
      <view class="notice-list">
        <view 
          v-for="notice in noticeList" 
          :key="notice.id" 
          class="notice-item"
          @click="goToNoticeDetail(notice.id)"
        >
          <view class="notice-content">
            <view class="notice-item-title">
              <view v-if="notice.isTop === 1" class="top-badge">置顶</view>
              <view v-if="notice.priority > 0" class="priority-badge" :class="getPriorityClass(notice.priority)">
                {{ getPriorityText(notice.priority) }}
              </view>
              <text class="notice-text">{{ notice.title }}</text>
            </view>
            <view class="notice-time">{{ formatTime(notice.createTime) }}</view>
          </view>
          <uni-icons type="right" size="14" color="#c0c0c0"></uni-icons>
        </view>
      </view>
    </view>
    
    <view class="header">
      <text class="title">配送订单</text>
    </view>
    <view class="tabs">
      <view 
        class="tab" 
        v-for="(item, index) in tabs" 
        :key="index"
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        <text>{{ item.text }}</text>
      </view>
    </view>
    <scroll-view 
      scroll-y 
      class="order-list" 
      @scrolltolower="loadOrders"
      :style="{ height: 'calc(100vh - 200rpx)' }"
    >
      <view v-if="orders.length === 0" class="empty-tip">
        <image class="empty-icon" src="/static/images/noData.png" mode="aspectFit"></image>
        <text class="empty-text">当前没有待处理订单哦~</text>
      </view>
      <view v-for="order in orders" :key="order.id" class="order-card">
        <!-- 顶部状态色条 -->
        <view class="order-status-bar" :style="{background: order.deliveryProcess === 0 ? '#07c160' : order.deliveryProcess === 1 ? '#ffb800' : '#34d399'}"></view>
        <!-- 商家信息区 -->
        <view class="order-header">
          <view class="merchant-info">
            <text class="merchant-name">{{ order.merchantName }}</text>
            <text class="order-status-tag" :class="'status-'+order.deliveryProcess">{{ order.deliveryProcessText }}</text>
          </view>
          <!-- 商家已出餐提示 -->
          <view v-if="currentTab === 1 && order.merchantProcess === 2" class="merchant-ready-badge">
            <text class="merchant-ready-text">商家已出餐</text>
          </view>
        </view>
        <view class="order-meta">
          <text class="order-id">订单号：{{ order.id }}</text>
        </view>
        <!-- 商品清单区 -->
        <view class="order-goods">
          <view class="goods-list">
            <view v-for="g in order.goods" :key="g.id" class="goods-item">
              <image class="goods-image" :src="g.image" mode="aspectFill"></image>
              <view class="goods-detail">
                <text class="goods-name">{{ g.name }}</text>
                <text class="goods-spec" v-if="g.specifications">{{ formatSpecifications(g.specifications) }}</text>
                <text class="goods-count">×{{ g.quantity }}</text>
                <text class="goods-price">￥{{ g.price }}</text>
              </view>
            </view>
          </view>
        </view>
        <!-- 时空信息区 -->
        <view class="order-meta">
          <text class="order-time"><span class="icon-clock">⏰</span> 下单时间：{{ order.createTime }}</text>
        </view>
        <view class="order-meta">
          <text class="delivery-time"><span class="icon-delivery">🚚</span> 预约送达时间：{{ getDeliveryTimeText(order.deliveryTimeType, order.scheduleTime) }}</text>
        </view>
        <view class="order-meta">
          <text class="receiver-name"><span class="icon-user">👤</span> 收货人：{{ order.receiverName }}</text>
        </view>
        <view class="order-meta">
          <text class="order-location"><span class="icon-location">📍</span> 送货地址：{{ order.deliveryAddress }}</text>
        </view>
        <view class="order-remark" v-if="order.remark">
          <text class="remark-label">✏️ 备注：</text><text class="remark-content">{{ order.remark }}</text>
        </view>
        <!-- 交易信息区 -->
        <view class="order-trade">
          <text class="order-actual">💰 实付￥{{ order.actualPay }}</text>
        </view>
        <view class="order-meta">
          <text class="order-fee">配送费：￥{{ order.deliveryFee }}</text>
        </view>
        <!-- 操作区 -->
        <view class="order-actions">
          <button class="detail-btn" @click="goToDetail(order.id)">订单详情</button>
          <button v-if="order.deliveryProcess===0 && !order.isGrabbed" class="grab-btn" @click="handleGrabOrder(order.id)">抢单</button>
          <button v-if="order.deliveryProcess===0 && order.isGrabbed" class="grabbed-btn" disabled>已被抢</button>
          <button v-if="order.deliveryProcess===1" class="confirm-btn" @click="handleConfirmPickup(order.id)">确认取货</button>
          <button v-if="order.deliveryProcess===2" class="complete-btn" @click="handleCompleteOrder(order.id)">确认送达</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getOrdersByDeliveryProcess, grabOrder, confirmPickup, completeOrder, getNoticeList, getNoticeDetail } from '@/api/order'
import { useUserStore } from '@/store/user'

const tabs = [
  { value: 0, text: '待抢单' },
  { value: 1, text: '待取餐' },
  { value: 2, text: '配送中' }
]
const currentTab = ref(0)
const switchTab = (idx) => { 
  currentTab.value = idx
  pageNo.value = 1
  finished.value = false
  loadOrders(true)
}

const orders = ref([])
const userStore = useUserStore()
const loading = ref(false)
const finished = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const noticeList = ref([])

// 处理订单状态变更的 WebSocket 消息
const handleOrderStatusChange = (data) => {
  console.log('收到订单状态变更:', data);
  
  // 查找对应的订单并更新状态
  const orderIndex = orders.value.findIndex(order => order.id === data.orderId);
  if (orderIndex !== -1) {
    const order = orders.value[orderIndex];
    
    // 如果是待抢单页面，且订单被抢了，则标记为已被抢
    if (currentTab.value === 0 && data.newDeliveryProcess === 1) {
      // 标记订单已被抢
      order.isGrabbed = true;
    }
  }
};

onMounted(() => {
  // 监听订单状态变更事件
  uni.$on('orderStatusChanged', handleOrderStatusChange);
});

onUnmounted(() => {
  // 移除事件监听
  uni.$off('orderStatusChanged', handleOrderStatusChange);
});

const formatSpecifications = (specsStr) => {
  try {
    const specs = JSON.parse(specsStr);
    if (!Array.isArray(specs)) return specsStr;
    return specs.map(spec => spec.value).join(',');
  } catch (e) {
    return specsStr;
  }
};

const getDeliveryTimeText = (deliveryTimeType, scheduleTime) => {
  if (deliveryTimeType === 1) {
    return '尽快送达';
  } else {
    return scheduleTime || '未设置';
  }
};

const loadOrders = async (reset = false) => {
  // 兼容滚动事件传入的情况
  if (typeof reset === 'object' && reset !== null) reset = false
  if (!reset && (loading.value || finished.value)) return
  
  loading.value = true
  const deliveryId = userStore.deliveryId
  const params = {
    deliveryProcess: tabs[currentTab.value].value,
    pageNo: pageNo.value,
    pageSize: pageSize.value
  }
  if (tabs[currentTab.value].value !== 0) {
    params.deliveryId = deliveryId
  }
  
  try {
    const res = await getOrdersByDeliveryProcess(params)
    if (reset) {
      orders.value = res.data.list
    } else {
      orders.value = [...orders.value, ...res.data.list]
    }
    
    if (res.data.list.length < pageSize.value) {
      finished.value = true
    } else {
      pageNo.value++
    }
  } catch (e) {
    console.error('加载订单失败:', e)
    uni.showToast({ title: '加载订单失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

onShow(() => {
  loadOrders(true)
  loadNotices()
})

const loadNotices = async () => {
  try {
    const res = await getNoticeList()
    noticeList.value = res.data || []
  } catch (e) {
    console.error('加载公告失败:', e)
  }
}

const goToNoticeDetail = (noticeId) => {
  uni.navigateTo({
    url: `/pages/notice/detail?id=${noticeId}`
  })
}

const getPriorityClass = (priority) => {
   switch (priority) {
     case 1: return 'priority-medium'
     case 2: return 'priority-high'
     default: return ''
   }
 }
 
 const getPriorityText = (priority) => {
   switch (priority) {
     case 1: return '重要'
     case 2: return '紧急'
     default: return ''
   }
 }

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}
const goToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/index/detail?id=${id}`
  });
};

const handleGrabOrder = async (orderId) => {
  try {
    const deliveryId = userStore.deliveryId;
    await grabOrder({ orderId, deliveryId });
    uni.showToast({ title: '抢单成功', icon: 'success' });
    loadOrders(true); // Refresh the list
  } catch (e) {
    console.error('抢单失败:', e);
    uni.showToast({ title: e.message || '抢单失败', icon: 'none' });
  }
};

const handleConfirmPickup = async (orderId) => {
  try {
    await confirmPickup({ orderId });
    uni.showToast({ title: '确认取货成功', icon: 'success' });
    loadOrders(true); // Refresh the list
  } catch (e) {
    console.error('确认取货失败:', e);
    uni.showToast({ title: e.message || '确认取货失败', icon: 'none' });
  }
};

const handleCompleteOrder = async (orderId) => {
  try {
    await completeOrder({ orderId });
    uni.showToast({ title: '确认送达成功', icon: 'success' });
    loadOrders(true); // Refresh the list
  } catch (e) {
    console.error('确认送达失败:', e);
    uni.showToast({ title: e.message || '确认送达失败', icon: 'none' });
  }
};
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.notice-section {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.notice-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.notice-title {
  display: flex;
  align-items: center;
}

.notice-title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}

.notice-list {
  padding: 0;
}

.notice-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s;
}

.notice-item:last-child {
  border-bottom: none;
}

.notice-item:active {
  background-color: #f8f8f8;
}

.notice-content {
  flex: 1;
  overflow: hidden;
}

.notice-item-title {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.top-badge {
  background-color: #007aff;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
}

.priority-badge {
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
}

.priority-medium {
  background-color: #ff9500;
}

.priority-high {
  background-color: #ff3b30;
}

.notice-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-time {
  font-size: 24rpx;
  color: #999;
}
.header {
  margin-bottom: 20rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}
.tabs {
    display: flex;
    margin-bottom: 32rpx;
    background: $bg-card;
    border-radius: 20rpx;
    padding: 8rpx;
    box-shadow: $shadow-sm;
    
    .tab {
      flex: 1;
      text-align: center;
      padding: 24rpx 0;
      font-size: 30rpx;
      color: $text-secondary;
      border-radius: 16rpx;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
    }
    
    .active {
      color: #ffffff;
      background: $bg-gradient;
      font-weight: 600;
      box-shadow: $shadow-primary;
    }
  }
.order-list {
  .order-card {
    @include card-style;
    margin-bottom: 32rpx;
    padding: 0 0 32rpx 0;
    position: relative;
    width: 100%;
    margin-left: 0;
    margin-right: 0;
  }
  .order-status-bar {
    height: 8rpx;
    width: 100%;
    border-radius: 24rpx 24rpx 0 0;
    margin-bottom: 0;
    background: $bg-gradient;
  }
  .order-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 24rpx 0 24rpx;
    position: relative;
    .merchant-info {
      display: flex;
      align-items: center;
      .merchant-name {
        font-size: 30rpx;
        color: #333;
        font-weight: bold;
        margin-right: 18rpx;
      }
      .order-status-tag {
        @include status-tag(rgba(102, 126, 234, 0.1), $primary-color);
        margin-right: 12rpx;
        
        &.status-1 { 
          @include status-tag(rgba(245, 158, 11, 0.1), #f59e0b);
        }
        &.status-2 { 
          @include status-tag(rgba(52, 211, 153, 0.1), $secondary-color);
        }
      }
      
    }
    .merchant-ready-badge {
      position: absolute;
      top: 12rpx;
      right: 12rpx;
      background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
      border-radius: 20rpx;
      padding: 8rpx 16rpx;
      box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
      animation: pulse 2s infinite;
      .merchant-ready-text {
        font-size: 24rpx;
        color: #ffffff;
        font-weight: 600;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
      }
    }
  }
  .order-goods {
    padding: 0 24rpx;
    margin-bottom: 8rpx;
    .goods-list {
      display: flex;
      flex-direction: column;
      .goods-item {
        display: flex;
        align-items: center;
        margin: 8rpx 0;
        .goods-image {
          width: 80rpx;
          height: 60rpx;
          border-radius: 8rpx;
          margin-right: 14rpx;
          flex-shrink: 0;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
          object-fit: cover;
        }
        .goods-detail {
          display: flex;
          flex-direction: row;
          align-items: baseline;
          flex-grow: 1; /* Allow detail to take available space */
          flex-wrap: wrap; /* Allow wrapping on smaller screens */
        }
        .goods-name {
          font-size: 30rpx; /* Increased font size */
          color: #333;
          font-weight: 500;
          margin-right: 16rpx;
          flex-shrink: 0; /* Prevent shrinking */
        }
        .goods-spec {
          font-size: 26rpx; /* Added style for spec */
          color: #888;
          margin-right: 16rpx;
        }
        .goods-count {
          font-size: 26rpx; /* Increased font size */
          color: #666;
          margin-right: 12rpx;
        }
        .goods-price {
          font-size: 28rpx; /* Increased font size */
          color: #e53e3e; /* Highlight price */
          font-weight: bold; /* Make price bold */
          margin-left: auto; /* Push price to the right */
        }
      }
    }
  }
  .order-meta {
    display: flex;
    align-items: center;
    font-size: 28rpx; /* Increased font size */
    color: #555; /* Slightly darker color for better contrast */
    padding: 0 24rpx;
    margin-bottom: 8rpx; /* Increased bottom margin */
    .receiver-name {
      margin-left: 0;
    }
    .order-time {
      margin-right: 32rpx;
      color: #ff6b00;
      .icon-clock { margin-right: 8rpx; } /* Adjusted icon spacing */
    }
    .delivery-time {
      color: #07c160;
      .icon-delivery { margin-right: 8rpx; } /* Adjusted icon spacing */
    }
    .order-location {
      .icon-location { margin-right: 8rpx; } /* Adjusted icon spacing */
    }
    .order-fee {
      font-size: 32rpx; /* Increased font size */
      color: #333;
      font-weight: bold;
      margin-top: 8rpx; /* Added top margin */
    }
  }
  .order-remark {
    padding: 0 24rpx;
    margin-bottom: 8rpx; /* Increased bottom margin */
    .remark-label {
      color: #ff6b00;
      font-size: 28rpx; /* Increased font size */
      font-weight: 500;
      margin-right: 8rpx; /* Adjusted spacing */
    }
    .remark-content {
      color: #e53e3e;
      font-size: 28rpx; /* Increased font size */
      font-weight: 500;
    }
  }
  .order-trade {
    padding: 0 24rpx;
    margin-bottom: 16rpx; /* Increased bottom margin */
    .order-actual {
      font-size: 28rpx; /* Increased font size */
      color: #333;
      font-weight: bold; /* Made actual pay bold */
    }
  }
  .order-fab-wrap {
    position: absolute;
    right: 32rpx;
    bottom: 32rpx;
    z-index: 2;
  }
  .order-fab-btn {
    @include btn-success;
    padding: 16rpx 32rpx;
    font-size: 28rpx;
    border-radius: 32rpx;
  }
  
  .order-fab-btn-orange {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    box-shadow: 0 8rpx 24rpx rgba(245, 158, 11, 0.15);
    
    &:active {
      box-shadow: 0 4rpx 12rpx rgba(245, 158, 11, 0.2);
    }
  }
  
  .order-fab-btn-blue {
    @include btn-primary;
    padding: 16rpx 32rpx;
    font-size: 28rpx;
    border-radius: 32rpx;
  }
}
body {
  background: #fff5f7;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 6rpx 16rpx rgba(255, 107, 53, 0.4);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.3);
  }
}
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
  }
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}
.detail-btn {
  background-color: #fff;
  border: 1px solid #1989fa;
  color: #1989fa;
  font-weight: 500;
  box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.1);
  margin-left: 24rpx;
  padding: 16rpx 36rpx;
  border-radius: 12rpx;
}
</style>

<style lang="scss">
  .order-actions {
    display: flex;
    gap: 8px;
    margin-top: 12px;
    
    button {
      flex: 1;
      padding: 10px 0;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      
      &.detail-btn {
        @include btn-secondary;
        padding: 20rpx 32rpx;
        font-size: 28rpx;
      }
      
      &.grab-btn {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: #ffffff;
        border: none;
        border-radius: 24rpx;
        padding: 20rpx 32rpx;
        font-size: 28rpx;
        font-weight: 600;
        box-shadow: 0 8rpx 24rpx rgba(245, 158, 11, 0.15);
        transition: all 0.3s ease;
        
        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 12rpx rgba(245, 158, 11, 0.2);
        }
      }
      
      &.grabbed-btn {
        background: #f5f5f5;
        color: #999;
        border: 1px solid #e0e0e0;
        border-radius: 24rpx;
        padding: 20rpx 32rpx;
        font-size: 28rpx;
        font-weight: 500;
        cursor: not-allowed;
        opacity: 0.6;
      }
      
      &.confirm-btn,
      &.complete-btn {
        @include btn-success;
        padding: 20rpx 32rpx;
        font-size: 28rpx;
      }
    }
  }
</style>
